package com.zhl.controller.user;

import com.zhl.controller.BaseServlet;
import com.zhl.model.Dept;
import com.zhl.model.User;
import com.zhl.service.DeptService;
import com.zhl.service.UserService;
import com.zhl.service.UserfocusService;
import com.zhl.service.impl.DeptServiceImpl;
import com.zhl.service.impl.UserServiceImpl;
import com.zhl.service.impl.UserfocusServiceImpl;
import com.zhl.utils.StrUtil;
import com.zhl.utils.page.PageEntity;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
public class userServlet extends BaseServlet {

    UserService userService = new UserServiceImpl();
    DeptService deptService = new DeptServiceImpl();
    UserfocusService userfocusService = new UserfocusServiceImpl();

    public void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String realName = req.getParameter("realName");
            User user = (User) req.getSession().getAttribute("userById");
            Map<String, String> param = getParam(req);
            Integer currPage;
            if (null == param.get("currPage") || "".equals(param.get("currPage"))) {
                currPage = 1;
            } else {
                currPage = Integer.parseInt(param.get("currPage"));
            }
            PageEntity<Map<String, Object>> userList = userService.findAll(realName,user.getId(),currPage);
            req.getSession().setAttribute("userList",userList);
            req.getRequestDispatcher("/html/user.jsp").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }





    public void userLook(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("userId");
        Map<String, Object> map = userService.findUserInfo(Integer.parseInt(id));
        List<Dept> depts = deptService.findDepts();
        req.setAttribute("depts",depts);
        req.setAttribute("userInfo",map);
        req.getRequestDispatcher("/html/user_look.jsp").forward(req,resp);
    }

    public void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        User user = (User) req.getSession().getAttribute("userById");
        String realName = req.getParameter("realName");
        user.setRealName(realName);
        String deptName = req.getParameter("deptName");
        user.setDeptName(deptName);
        Dept dept = deptService.findDeptByName(deptName);
        user.setDeptId(dept.getId());
        String phone = req.getParameter("phone");
        user.setPhone(phone);
        String age = req.getParameter("age");
        user.setAge(Integer.parseInt(age));
        String gender = req.getParameter("gender");
        user.setGender(gender);
        String is_secret = req.getParameter("is_secret");
        if (is_secret == null){
            is_secret = "1";
        }
        user.setIsSecret(is_secret);
        userService.updateUser(user,user.getId());
        Map<String, Object> user1 = userService.findUserAndDeptById(user.getId());
        req.getSession().setAttribute("user",user1);
        resp.sendRedirect(req.getContextPath() + "/user/userLook?userId=" + user.getId());
    }

    public void userDetail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userId = req.getParameter("userId");
        Map<String, Object> mapById = userService.findUserInfo(Integer.parseInt(userId));
        req.setAttribute("userInfoById",mapById);
        userService.updateLookById(Integer.parseInt(userId));
        req.getRequestDispatcher("/html/user_detail.jsp").forward(req,resp);
    }

    public void focus(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String id = req.getParameter("uId");
        User user = (User)req.getSession().getAttribute("userById");
        Integer focus = userfocusService.findUserfocusById(user.getId(), Integer.parseInt(id));
        resp.getWriter().write(String.valueOf(focus));
    }

    public void userFocus(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        User user = (User) req.getSession().getAttribute("userById");
        List<Map<String, Object>> userFocus = userService.findFocus(user.getId());
        req.getSession().setAttribute("userFocus",userFocus);
        req.getRequestDispatcher("/html/my_user.jsp").forward(req,resp);
    }

    //更新头像
    public void updateImg(HttpServletRequest req, HttpServletResponse resp){
        try {
            ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> items = fileUpload.parseRequest(req);
            if (items.size() > 0) {
                FileItem item = items.get(0);
                int index = item.getName().lastIndexOf(".");
                String suffix;
                if (-1 != index) {
                    suffix = item.getName().substring(index + 1);
                } else {
                    suffix = "jpg";
                }
                String fileName = StrUtil.getUUID() + "." + suffix;
                File target = new File("E:\\work\\resources\\img\\" + fileName);
                item.write(target);
                //下一步，更新用户头像路径
                String path = "/img/" + fileName;
                User user = (User) req.getSession().getAttribute("userById");
                user.setPic(path);
                userService.updateUser(user,user.getId());
                resp.getWriter().write(path);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
